#include "resetpswdialog.h"
#include "ui_resetpswdialog.h"
#include<QJsonDocument>
#include"toast.h"
#include<httpmgr.h>
#include<QString>
#include<QMap>
ResetpswDialog::ResetpswDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ResetpswDialog)
{
    ui->setupUi(this);
    InitHandler();
    setupconnection();
}

ResetpswDialog::~ResetpswDialog()
{
    delete ui;
}

void ResetpswDialog::on_cancel_btn_clicked()
{
    emit SwitchToLogin();
}

void ResetpswDialog::InitHandler(){
    m_handler.insert({ID_GET_VARIFY_CODE,
                      std::function<void(QJsonObject&)>([this](QJsonObject &jobj)
                                                         {
                                                             int error = jobj["error"].toInt();
                                                             auto msg=jobj["msg"].toString();
                                                             if(error != Ecode::SUCCESS){
                                                                 //ShowTip("参数出错", false);
                                                                 Toast::error(msg,this);
                                                                 return;
                                                             }
                                                             emit countdown();
                                                             auto email = jobj["email"].toString();
                                                             //ShowTip("验证码已经发送，请查收", true);
                                                             Toast::info("验证码已经发送，请查收",this);
                                                             qDebug()<<email;
                                                         })});

    m_handler.insert({ID_RESET_PSW,[this](QJsonObject &json){


                          auto error=json["error"].toInt();
                          auto msg=json["msg"].toString();
                          if(error!=Ecode::SUCCESS){
                              Toast::error(msg,this);
                              return;
                          }
                          Toast::success("密码重置成功，请返回登陆界面");
                      }});
}

void ResetpswDialog::setupconnection(){
    connect(_HttpMgr::GetInstance().get(),&HttpMgr::sig_resetpsw_http_finish,this,&ResetpswDialog::slot_req_finish_http);
    connect(ui->email_edit,&QLineEdit::editingFinished,this,&ResetpswDialog::onEmailTextChanged);
    connect(ui->psw_edit,&QLineEdit::editingFinished,this,&ResetpswDialog::onPasswordTextChanged);
    connect(ui->repsw_edit,&QLineEdit::editingFinished,this,&ResetpswDialog::onRepswTextChanged);
    connect(ui->varify_code,&QLineEdit::textChanged,this,&ResetpswDialog::onVerifyTextChanged);
    connect(this,&ResetpswDialog::countdown,ui->get_code_btn,&VerificationCodeButton::onButtonClicked);
}

void ResetpswDialog::onEmailTextChanged(){
    auto text=ui->email_edit->text();
    if(validateField("email",text)){
        m_errormgr.removeError("email");
        ui->email_edit->setStyleSheet("border:2px solider green;");
    }
}

void ResetpswDialog::onPasswordTextChanged(){
    auto text=ui->psw_edit->text();
    if(validateField("password",text)){
        m_errormgr.removeError("password");
        ui->psw_edit->setStyleSheet("border:2px solider green;");
    }
}

void ResetpswDialog::onRepswTextChanged(){
    auto text=ui->repsw_edit->text();
    if(validateField("repsw",text)){
        m_errormgr.removeError("repsw");
        ui->repsw_edit->setStyleSheet("border:2px solider green;");
    }
}

void ResetpswDialog::onVerifyTextChanged(const QString& text){
    if(validateField("verify",text)){
        m_errormgr.removeError("verify");
        ui->repsw_edit->setStyleSheet("border:2px solider green;");
    }
}

bool ResetpswDialog::validateField(const QString& fieldId,const QString &value){
     if (fieldId == "password") {
        if (value.length() < 6) {
            m_errormgr.addError("password", "密码至少需要6个字符");
            ui->psw_edit->setStyleSheet("border: 2px solid red;");
            return false;
        }
        if (value.length() > 15) {
            m_errormgr.addError("password", "密码不能超过15个字符");
            ui->psw_edit->setStyleSheet("border: 2px solid red;");
            return false;
        }
        QRegularExpression regExp("^[a-zA-Z0-9!@#$%^&*]{6,15}$");
        if (!regExp.match(value).hasMatch()) {
            m_errormgr.addError("password", "密码只能包含字母、数字和!@#$%^&*");
            ui->psw_edit->setStyleSheet("border: 2px solid red;");
            return false;
        }
        return true;
    }
    else if (fieldId == "email") {

        QRegularExpression regex(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
        if (!regex.match(value).hasMatch()) {
            m_errormgr.addError("email", "邮箱地址格式不正确");
            ui->email_edit->setStyleSheet("border: 2px solid red;");
            return false;

        }

        return true;
    }
    else if (fieldId == "verify") {
        if (value.isEmpty()) {
            m_errormgr.addError("verify", "验证码不能为空");
            ui->varify_code->setStyleSheet("border: 2px solid red;");
            return false;
        }
        return true;
    }
    else if(fieldId=="repsw"){
        if(value.isEmpty()){
            m_errormgr.addError("repsw","请确认密码");
            ui->repsw_edit->setStyleSheet("border: 2px solid red;");
            return false;
        }

        auto text=ui->psw_edit->text();
        if(text!=value){
            m_errormgr.addError("repsw","两次密码密码不一致");
            ui->repsw_edit->setStyleSheet("border: 2px solid red;");
            return false;
        }
    }

    return true;
}


void ResetpswDialog::slot_req_finish_http(ReqId id,QString res,Ecode error){
    if(error!=Ecode::SUCCESS){
        Toast::error("网络错误",this);
        return;
    }

    QJsonDocument jdoc=QJsonDocument::fromJson(res.toUtf8());
    if(jdoc.isNull()||!jdoc.isObject()){
        Toast::error("json 解析错误",this);
        return;
    }


    QJsonObject jobj=jdoc.object();
    m_handler[id](jobj);
}


void ResetpswDialog::on_get_code_btn_clicked()
{
    m_errormgr.clearAllErrors();
    bool validall=true;
    if(!validateField("email",ui->email_edit->text())) validall=false;
    if(!validateField("password",ui->psw_edit->text())) validall=false;
    if(!validateField("repsw",ui->repsw_edit->text())) validall=false;

    if(validall){
        QJsonObject json;
        json["email"]=ui->email_edit->text();
        _HttpMgr::GetInstance()->PostHttpReq(QUrl("http://localhost:8080/get_varifycode"),json,ReqId::ID_GET_VARIFY_CODE,MoudleId::RESETPSW);
    }
    else{
         qDebug() << "发现" << m_errormgr.errorCount() << "个错误，将按顺序显示";
    }
}


void ResetpswDialog::on_confirm_btn_clicked()
{
    m_errormgr.clearAllErrors();
    bool validall=true;
    if(!validateField("email",ui->email_edit->text())) validall=false;
    if(!validateField("password",ui->psw_edit->text())) validall=false;
    if(!validateField("repsw",ui->repsw_edit->text())) validall=false;

    if(validall){
        QJsonObject json;
        json["email"]=ui->email_edit->text();
        json["password"]=ui->psw_edit->text();
        json["repsw"]=ui->repsw_edit->text();
        _HttpMgr::GetInstance()->PostHttpReq(QUrl("http://localhost:8080/user_resetpsw"),json,ReqId::ID_RESET_PSW,MoudleId::RESETPSW);
    }
    else{
        qDebug() << "发现" << m_errormgr.errorCount() << "个错误，将按顺序显示";
    }
}

